package com.lj.mcore.service;

import com.lj.mcore.dao.base.BaseAppDAO;
import com.lj.mcore.entity.Goods;
import com.lj.mcore.entity.GoodsSpecProperty;
import com.lj.mcore.entity.GoodsSpecification;
import com.lj.mcore.entity.GoodsStock;
import com.lj.mcore.execption.OutOfStockException;
import com.lj.mcore.utils.CommUtils;
import com.lj.mcore.utils.PageBean;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public class GoodsService implements IGoodsService{

    @Resource(name="goodsDao")
    private BaseAppDAO<Goods> goodsDao;

    @Autowired
    IGoodsStockService goodsStockService;

    @Autowired
    IGoodsSpecificationService goodsSpecificationService;

    @Autowired
    IGoodsSpecPropertyService goodsSpecPropertyService;

    @Override
    public boolean save(Goods paramUser) {
        return goodsDao.save(paramUser);
    }

    @Override
    public boolean saveWithStock(Goods obj, List<GoodsStock> stocks) {
        //设置规格
        List<GoodsSpecification> specifications = obj.getSpecifications();
        for(GoodsSpecification specification:specifications)
        {
            goodsSpecificationService.save(specification);
            for (GoodsSpecProperty specProperty:specification.getProperties()){
                specProperty.setSpec(specification);
                goodsSpecPropertyService.save(specProperty);
            }
        }

        goodsDao.save(obj);

        //设置库存
        for (GoodsStock goodsStock :stocks){
            goodsStock.setGoods(obj);
            String idPath = goodsStock.getIdPath();
            if (!CommUtils.null2String(idPath).equals("")){
                String[] idPaths = idPath.split("/");
                String key = "";
                for (String temp_idPath:idPaths){
                    String[] paths = temp_idPath.split("_");
                    key += specifications.get(Integer.valueOf(paths[0])).getProperties().get(Integer.valueOf(paths[1])).getId()+"/";
                }
                key = key.substring(0,key.length()-1);
                goodsStock.setKey(key);
            }
            goodsStockService.save(goodsStock);
        }
        return true;
    }

    @Override
    public boolean delete(Long paramLong) {
        return false;
    }

    @Override
    public boolean update(Goods paramUser) {
        return goodsDao.update(paramUser);
    }

    @Override
    public boolean updateWithStock(Goods obj, List<GoodsStock> stocks)  {
        int i= 0;
        for (GoodsStock goodsStock :stocks){
            /*try {
                goodsStockService.update(goodsStock);
            }catch (OutOfStockException e){
                throw  new OutOfStockException(e.getMessage());
            }catch (OptimisticLockingFailureException e){
                throw  new OptimisticLockingFailureException(e.getMessage());
            } catch (Exception e){
                throw e;
            }*/
            i++;
            goodsStockService.update(goodsStock);
            System.out.println("i++ ==" +i);
        }

        System.out.println("&&&&&&&&&&&&&&&&&&&&&&");
        goodsDao.update(obj);
        return true;
    }

    @Override
    public Goods getObjById(Long paramLong) {
        return goodsDao.findById(paramLong);
    }

    @Override
    public Goods getSingleResult(Map<String, Object> map) {
        return null;
    }

    @Override
    public List<Goods> query(String paramString, Map paramMap, int paramInt1, int paramInt2) {
        return goodsDao.query(paramString, paramMap, paramInt1, paramInt2);
    }

    @Override
    public PageBean getList(int pageSize, int page, Map<String, String> query) {
        StringBuffer sb = new StringBuffer("from Goods obj where obj.deleteStatus = false ");
        if(query != null && query.size() >0 ){

            if(!CommUtils.null2String(query.get("goods_name")).equals("")){
                sb.append(" and obj.goods_name = '"+query.get("goods_name")+"' ");
            }
        }
        sb.append(" order by obj.addTime desc");

        String hql = sb.toString();

        List listNum = this.query("select count(obj.id) "+hql,null,0,1);
        int allRow=0;
        if (listNum!=null){
            allRow = CommUtils.null2Int(listNum.get(0));
        }
        int totalPage = PageBean.countTotalPage(pageSize, allRow);
        final int offset = PageBean.countOffset(pageSize, page);
        final int length = pageSize;
        final int currentPage = PageBean.countCurrentPage(page);
        List list = this.query(hql,null, offset, length);
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setAllRow(allRow);
        pageBean.setTotalPage(totalPage);
        pageBean.setList(list);
        pageBean.init();
        return pageBean;
    }

    public int checkGoodsSerial(String goods_serial){
        String hql = "select count(obj.id) from Goods obj where obj.deleteStatus = false and obj.goods_serial=:goods_serial";
        Map queryMap = new HashMap();
        queryMap.put("goods_serial",goods_serial);
        List list = query(hql,queryMap,-1,-1);
        return CommUtils.null2Int(list.get(0));
    }
}
